import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/pages/home/noticeApi.dart';
import 'package:ct_pa_majordomo/router/keys.dart';
import 'package:ct_pa_majordomo/utils/date_tools.dart';
import 'package:ct_pa_majordomo/utils/stacker.dart';
import 'package:ct_pa_majordomo/widgets/normal_scaffold/index.dart';
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import 'package:flutter/material.dart';
import "package:flutter_easyloading/flutter_easyloading.dart";

class NoticeList extends StatefulWidget {
  const NoticeList({Key? key}) : super(key: key);

  @override
  _NoticeListState createState() => _NoticeListState();
}

class _NoticeListState extends State<NoticeList> {
  final ScrollController _scrollController = ScrollController();
  List _noticeList = [];
  bool _isLoading = false;
  bool _isEditing = false;
  List<String> _selectedIds = [];
  int _total = 0;
  final Map<String, dynamic> _filter = {"pageNum": 1,};

  
  @override
  void initState() {
    super.initState();
    _refresh();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  Future<void> _refresh() async {
    _filter["pageNum"] = 1;
    _noticeList = [];
    _fetchNoticeList();
  }
  
  // 获取消息列表
  Future<void> _fetchNoticeList() async {
    setState(() {
      _isLoading = true;
    });
    
    try {
      EasyLoading.show();
      final result = await noticeApi.getNoticeList(_filter);
      if (result['code'] == 200) {
        setState(() {
          _total = result["total"];
          _noticeList.addAll(result['rows'] ?? []);
        });
      }
    } catch (e) {
      print('Error fetching notice list: $e');
    } finally {
      EasyLoading.dismiss();
      setState(() {
        _isLoading = false;
      });
    }
  }
  
  // 批量删除消息
  Future<void> _batchDeleteNotice() async {
    if (_selectedIds.isEmpty) return;
    taiDialog(
      context: context,
      title: "确定删除？",
      onConfirm: (taiContext) async {
        try {
          final result = await noticeApi.batchDeleteNotice(_selectedIds.join(","));
          if (result['code'] == 200) {
            // 删除成功后重新获取列表
            _refresh();
            // 重置编辑状态
            setState(() {
              _isEditing = false;
              _selectedIds = [];
            });
          }
          Stacker.pop();
        } catch (e) {
          print('Error deleting notices: $e');
        }
      },
      onCancel: (taiContext) {
        Stacker.pop();
      }
    );

  }
  
  // 切换选择状态
  void _toggleSelect(String noticeId) {
    setState(() {
      if (_selectedIds.contains(noticeId)) {
        _selectedIds.remove(noticeId);
      } else {
        _selectedIds.add(noticeId);
      }
    });
  }
  
  // 全选
  void _selectAll() {
    setState(() {
      if (_selectedIds.length == _noticeList.length) {
        // 如果已全选，则取消全选
        _selectedIds = [];
      } else {
        // 全选
        _selectedIds = _noticeList.map((notice) => notice['notificationId'].toString()).toList();
      }
    });
  }
  
  // 取消编辑
  void _cancelEdit() {
    setState(() {
      _isEditing = false;
      _selectedIds = [];
    });
  }
  
  // 进入消息详情页
  void _navigateToDetail(Map<String, dynamic> notice) {
    if (!_isEditing) {
      Stacker.pushNamed(
        Keys.NOTICE_DETAIL, 
        arguments: {
          'notificationId': notice['notificationId'],
          'title': notice['title'],
        }
      ).then((value) {
        _refresh();
      });
    }
  }

  void _onScroll() {
    if (_isLoading || _noticeList.length >= _total) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      print("ddd");
      setState(() {
        _filter["pageNum"] += 1;
        _fetchNoticeList();
      });
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: '消息列表',
      actions: [
        TextButton(
          onPressed: () {
            if (_isEditing) {
              _selectAll();
            } else {
              setState(() {
                _isEditing = !_isEditing;
                _selectedIds = []; // 切换编辑状态时清空选择
              });
            }
          },
          child: Text(
            _isEditing ? '全选' : '编辑',
            style: const TextStyle(color: Colors.white),
          ),
        ),
      ],
      child: Stack(
        children: [
          _noticeList.isEmpty
                  ? const Center(child: Text('暂无消息'))
                  : RefreshIndicator(
                      onRefresh: _refresh,
                      child: ListView.separated(
                        controller: _scrollController,
                        physics: const AlwaysScrollableScrollPhysics(),
                        padding: EdgeInsets.only(left: ThemeVars.paddingPage, right: ThemeVars.paddingPage, top: 8, bottom: _isEditing ? 72 : 6),
                        itemCount: _noticeList.length,
                        separatorBuilder: (context, index) => const Divider(),
                        itemBuilder: (context, index) {
                          final notice = _noticeList[index];
                          final bool isRead = notice["status"] == "1" ? true : false;

                          return GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () => _navigateToDetail(notice),
                            child: Container(
                              padding: const EdgeInsets.symmetric(vertical: 8),
                              child: Row(
                                children: [
                                  if (_isEditing) ...[
                                    Padding(
                                      padding: const EdgeInsets.only(right: 12),
                                      child: GestureDetector(
                                        onTap: () => _toggleSelect(notice['notificationId'].toString()),
                                        child: Container(
                                          width: 24,
                                          height: 24,
                                          decoration: BoxDecoration(
                                            shape: BoxShape.circle,
                                            border: Border.all(
                                              color: ThemeVars.colorPrimary,
                                              width: 1,
                                            ),
                                            color: _selectedIds.contains(notice['notificationId'].toString())
                                                ? ThemeVars.colorPrimary
                                                : Colors.white,
                                          ),
                                          child: _selectedIds.contains(notice['notificationId'].toString())
                                              ? const Icon(Icons.check, size: 16, color: Colors.white)
                                              : null,
                                        ),
                                      ),
                                    ),
                                  ],
                                  Expanded(
                                    child: Row(
                                      children: [
                                        Expanded(
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                children: [
                                                  Container(
                                                    child: Text(
                                                      notice['title'] ?? '',
                                                      style: TextStyle(
                                                        fontSize: 15,
                                                        fontWeight: isRead ? FontWeight.normal : FontWeight.bold,
                                                      ),
                                                      maxLines: 1,
                                                      overflow: TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                                  const SizedBox(width: 8),
                                                  Expanded(
                                                    child: Text(
                                                      notice['content'] ?? '',
                                                      style: TextStyle(
                                                        fontSize: 14,
                                                        color: ThemeVars.colorTextSec,
                                                      ),
                                                      maxLines: 1,
                                                      overflow: TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                              const SizedBox(height: 4),
                                              Text(
                                                notice['createTime'],
                                                style: TextStyle(
                                                  fontSize: 12,
                                                  color: ThemeVars.colorTextTer,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                        if (!isRead)
                                          Container(
                                            width: 8,
                                            height: 8,
                                            margin: const EdgeInsets.only(right: 8),
                                            decoration: const BoxDecoration(
                                              shape: BoxShape.circle,
                                              color: ThemeVars.colorWarning,
                                            ),
                                          ),
                                      ],

                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                    )
                  ),
          
          // 底部悬浮操作栏
          if (_isEditing)
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                decoration: BoxDecoration(
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      spreadRadius: 1,
                      blurRadius: 3,
                      offset: const Offset(0, -1),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    TextButton(
                      onPressed: _cancelEdit,
                      child: const Text('取消'),
                    ),
                    TextButton(
                      onPressed: _selectedIds.isNotEmpty ? _batchDeleteNotice : null,
                      child: Text(
                        '删除',
                        style: TextStyle(
                          color: _selectedIds.isNotEmpty
                              ? Colors.red
                              : Colors.red.withOpacity(0.5),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }
} 